package xin.nick.common.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import xin.nick.common.core.util.UserIdUtil;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 实体类填充
 *
 * @author Nick
 * @since 2022/10/26/026
 */
@Slf4j
@Component
public class MyMetaHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        Long userId = UserIdUtil.getUserIdNotCheck();
        if (Objects.nonNull(userId)) {
            this.strictInsertFill(metaObject, "createUserId", Long.class, userId);
            this.strictInsertFill(metaObject, "updateUserId", Long.class, userId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        Long userId = UserIdUtil.getUserIdNotCheck();
        if (Objects.nonNull(userId)) {
            this.strictUpdateFill(metaObject, "updateUserId", Long.class, userId);
        }
    }
}
